import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import Select from '@kuiper-components/select';
import Pagination from '@kuiper-components/pagination';

import Empty from '../empty/EmptyData';
import s from './LocalPagingTable.module.css';

export default function LocalPagingTable({
	className,
	tableData,
	filter,
	onFilter,
	page,
	onPage,
	columns,
}) {
	const [perPage, setPerPage] = React.useState(10);

	const { dataSource, total } = React.useMemo(() => {
		const currentFilter = JSON.parse(JSON.stringify(filter));
		const initTableData = onFilter({ filter: currentFilter, data: tableData });
		const dataSource = initTableData.slice(
			(page - 1) * perPage,
			page * perPage
		);
		return { dataSource, total: initTableData?.length || 0 };
	}, [tableData, filter, page, perPage]);

	const handleSizeChange = (current, size) => {
		setPerPage(size);
	};

	return (
		<div className={cn(className, s.localPagingTable)}>
			<div className={s.tableContainer}>
				<table className={s.table}>
					<thead>
						<tr>
							{columns.map(col => (
								<th
									key={col.key}
									style={{
										width: col.width || 'auto',
									}}
									className={cn(s.headerItem, col.className)}
								>
									{col.title}
								</th>
							))}
						</tr>
					</thead>
					<tbody>
						{dataSource.map(row => (
							<tr key={row._id}>
								{columns.map(c => {
									const val = row[c.dataIndex];
									return (
										<td key={c.key} className={s.item}>
											{c.render ? c.render(val, row) : val}
										</td>
									);
								})}
							</tr>
						))}
					</tbody>
				</table>
				{dataSource.length === 0 && <Empty borderless />}
			</div>
			{total > perPage && (
				<div className={s.pageContainer}>
					<Pagination
						total={total}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						pageSize={perPage}
						current={page}
						onChange={num => onPage(num)}
						onShowSizeChange={handleSizeChange}
						selectComponentClass={Select}
					/>
				</div>
			)}
		</div>
	);
}

LocalPagingTable.propTypes = {
	className: PropTypes.string,
	tableData: PropTypes.arrayOf(PropTypes.object),
	filter: PropTypes.object,
	perPage: PropTypes.number,
	page: PropTypes.number,
	onFilter: PropTypes.func,
	columns: PropTypes.array,
	onPage: PropTypes.func.isRequired,
};

LocalPagingTable.defaultProps = {
	className: s.localPagingTable,
	tableData: [],
	columns: [],
	filter: {},
	// perPage: 10,
	page: 1,
	onFilter: ({ data, filter }) => {
		const filterArr = Object.entries(filter);
		const res = data.filter(row => {
			return filterArr.every(([key, val]) => {
				return val === row[key].toString() || val === '';
			});
		});
		return res;
	},
};
